package com.learn.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class HelloController {
    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);

    @Resource
    private DiscoveryClient client;
    @Resource
    private Registration registration;

    @GetMapping("/hello")
    public String index(){
        ServiceInstance instance = serviceInstance();
        logger.info("/hello,host:{}",instance.getHost() + ",service_id:{}",instance.getServiceId());
        return "Hello world";
    }
    public ServiceInstance serviceInstance(){
        List<ServiceInstance> instances = client.getInstances(registration.getServiceId());
        if(instances!=null && instances.size() > 0){
            for(ServiceInstance instance: instances){
                if(instance.getServiceId().equals("HELLO-SERVICE")){
                    return instance;
                }
            }
        }
        return null;
    }
}
